package com.tb.dubbo_service;

import com.tb.dubbo.ISolrService;
import com.tb.mapper.GoodsMapper;
import com.tb.pojo.Goods;
import com.tb.utils.ReturnList;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 何龙
 * @create 2019-01-10 21:41
 */
@Service
public class SoleServiceImp implements ISolrService {

    private final String SEARCH_BASE_URL="http://39.107.253.13:8082/solr";

    @Autowired
    private GoodsMapper goodsMapper;
    @Override
    public boolean addSolr() {


        HttpSolrServer solrServer = new HttpSolrServer(SEARCH_BASE_URL);

        //      删除所有索引
        try {
            HttpSolrServer solrServer2 = new HttpSolrServer(SEARCH_BASE_URL);
            solrServer2.deleteByQuery("*:*");
            solrServer2.commit();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }


        /*查询所有商品列表*/
        Map<String,Object> map = new HashMap<>();
        map.put( "goods_sold","" );
        List<Goods> goods = goodsMapper.selectGoodsBysold( map );

        SolrInputDocument document;

        try {

            for (Goods good : goods) {
                document = new SolrInputDocument();
                document.addField("id", good.getGoodsId());
                document.addField("goodsName", good.getGoodsName());
                document.addField("goodsPrice", good.getGoodsPrice() );
                document.addField("goodsSold", good.getGoodsSold());
                document.addField("goodsComments", good.getGoodsComments());
                document.addField("goodsImg", good.getImg());

                solrServer.add(document);
            }

            solrServer.commit();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * solr站内搜索
     * @param goosName 商品名
     * @param page 页码数
     * @param rows 每页数目
     * @param sort 销量排序方式，降序
     * @param goodsPrice 价格排序
     * @return 查询后商品列表
     */
    @Override
    public ReturnList getSolr(
            String goosName, Integer page,
            Integer rows ,String sort,
            String goodsPrice) {

        HttpSolrServer server = new HttpSolrServer(SEARCH_BASE_URL);

        SolrQuery query = new SolrQuery();

        if(StringUtils.isEmpty(goosName)){
            query.setQuery("*:*");
        }else{
            query.setQuery(goosName);
        }



        //	设置默认的搜索域
        query.set("df", "goodsName");

        // 设置查询的排序参数，1-排序的字段名，2-排序方式（ORDER：asc desc）
        //设置排序

        if (!"".equals(sort)){
            query.addSort("goodsSold", SolrQuery.ORDER.desc);
        }

        if (!"".equals(goodsPrice)&&"asc".equals(goodsPrice)){

            query.addSort("goodsPrice", SolrQuery.ORDER.asc);

        } else if (!"".equals(goodsPrice)&&"desc".equals(goodsPrice)){

            query.addSort("goodsPrice", SolrQuery.ORDER.desc);

        }
        //设置起始条数
        query.setStart((page-1)*rows);

        //设置每页条数
        query.setRows(rows);

        try {
            QueryResponse response = server.query(query);

            SolrDocumentList list = response.getResults();


            List<Goods> lsd = new ArrayList();

            Goods g;

            for (SolrDocument sd : list) {
                g = new Goods();

                g.setGoodsId((String)sd.getFieldValue("id"));
                g.setGoodsName((String)sd.getFieldValue("goodsName"));
                g.setGoodsPrice((Float) sd.getFieldValue("goodsPrice"));
                g.setGoodsSold((Integer) sd.getFieldValue("goodsSold"));
                g.setGoodsComments((Integer)sd.getFieldValue("goodsComments"));
                g.setImg((String) sd.getFieldValue("goodsImg"));

                lsd.add(g);
            }
            return ReturnList.get( numFound(goosName),lsd );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ReturnList.get( 0L,null );
    }

    //获取总索引数
    private Long numFound(String str)throws Exception{

        SolrServer solrServer = new HttpSolrServer(SEARCH_BASE_URL);
        //创建一个文档对象SolrInputDocument

        //构造搜索条件
        SolrQuery solrQuery = new SolrQuery();
        if(StringUtils.isEmpty(str)){
            solrQuery.setQuery("*:*");
        }else{
            solrQuery.setQuery(str);
        }
        //	设置默认的搜索域
        solrQuery.set("df", "goodsName");
        // 执行查询
        QueryResponse queryResponse = solrServer.query(solrQuery);
        SolrDocumentList list=queryResponse.getResults();
        //获取总索引数

        return list.getNumFound();

    }
}
